<template>
  <div class="container-fluid">
    <div class="row school-model school-tiao">
      <div class="col school-tiao-left">
        <span>{{ clazz.name }} | {{ $route.name }}</span>
      </div>
      <div class="col text-right">
        <a-button-group>
          <a-button type="primary" @click="visibletrue">查看排课</a-button>
          <a-button type="primary">
            <router-link :to="{name:'班级'}" class="text-white">返回</router-link>
          </a-button>
        </a-button-group>
      </div>
    </div>
    <div class="row school-model index-model">
      <div class="col-lg-12 school-col-table">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" size="mini">
          <el-form-item label="排课类型">
            <el-radio-group v-model="type">
              <el-radio :label="false">单次课</el-radio>
              <el-radio :label="true">系列课</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-show="settableshow" v-if="!type" label="上课日期" prop="starttime">
            <el-date-picker
              v-model="ruleForm.starttime"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </el-form-item>
          <el-form-item v-show="settableshow" v-else label="上课日期">
            <el-date-picker
              v-model="ruleForm.value1"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </el-form-item>
          <el-form-item v-show="settableshow" label="上课时段" prop="schoolclasstime">
            <el-select v-model="ruleForm.schoolclasstime" allow-create placeholder="请选择时间段">
              <el-option
                v-for="(item, i) in returnschoolclasstime"
                :key="`2clazzschedule${i}`"
                :label="`${item.starttime}-${item.endtime}`"
                :value="`${item.starttime}-${item.endtime}`"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-show="settableshow" label="课时" prop="hour">
            <el-input-number v-model="ruleForm.hour" :min="1" :max="10" label="描述文字"></el-input-number>
          </el-form-item>
          <el-form-item v-show="settableshow" label="重复方式" v-if="type">
            <el-select v-model="ruleForm.repeat" allow-create placeholder="请选择重复方式">
              <el-option label="每周重复" :value="true"></el-option>
              <el-option label="隔周重复" :value="false"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-show="settableshow" label="过滤节假日" v-if="type">
            <el-radio-group v-model="ruleForm.holiday">
              <el-radio :label="false">是</el-radio>
              <el-radio :label="true">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-show="settableshow" label="时间周期" v-if="type" prop="checkList">
            <el-checkbox-group class="checkbox-group" v-model="ruleForm.checkList">
              <el-checkbox
                v-for="(v, i) in [ {name:'一',value:1}, {name:'二',value:2}, {name:'三',value:3}, {name:'四',value:4}, {name:'五',value:5}, {name:'六',value:6},{name:'日',value:7}]"
                :key="`3clazzschedule${i}`"
                :label="v.value"
                :value="v.value"
              >{{`周${v.name}`}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item v-show="settableshow" label="教室" prop="schoolclassroomid">
            <el-select v-model="ruleForm.schoolclassroomid" allow-create placeholder="请选择教室">
              <el-option
                v-for="(item, i) in classroom"
                :key="`4clazzschedule${i}`"
                :label="item.name"
                :value="item.ID"
                :disabled="item.studentnum<clazz.studentnum"
              >
                <span style="float: left">{{ item.name }}</span>
                <span
                  style="float: right; color: #8492a6; font-size: 13px"
                >可容纳{{ item.studentnum }}人</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-show="settableshow" label="教师" prop="schooluserid">
            <el-select v-model="ruleForm.schooluserid" allow-create placeholder="请选择教师">
              <el-option
                v-for="(item, i) in user"
                :key="`5clazzschedule${i}`"
                :label="item.name"
                :value="item.ID"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-show="settableshow" label="助教">
            <el-select v-model="ruleForm.schooluserids" allow-create placeholder="请选择助教">
              <el-option
                v-for="(item, i) in getschooluser.filter(v=> !v.state)"
                :key="`6clazzschedule${i}`"
                :label="item.name"
                :value="item.ID"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-show="!type && settableshow" label="课程内容">
            <el-input style="max-width:300px;" v-model="ruleForm.info" clearable placeholder="课程内容"></el-input>
          </el-form-item>
          <el-form-item v-show="settableshow">
            <el-button @click="submitForm">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="col-lg-12 school-col-table" v-show="tableData.length && !settableshow">
        <el-form label-width="100px" size="mini">
          <el-form-item label="上课安排">
            <div class="row">
              <div class="col">
                <span class="text-primary">
                  计划安排
                  <span v-text="pushdatacoursenum.length"></span>次课
                </span>
                <span class="text-primary">
                  共
                  <span v-text="pushdatacoursenum.hour"></span>课时
                </span>
              </div>
              <div class="col text-right">
                <el-button type="primary" @click="settableshow = true">添加安排</el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="课程">
            <el-select
              v-model="courseindex"
              :disabled="!!clazz.schoolcourseid"
              allow-create
              placeholder="请选择课程"
            >
              <el-option
                v-for="(item, i) in getschoolcourse"
                :key="`8clazzschedule${i}`"
                :label="item.name"
                :value="item.ID"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-table :data="tableData" style="width: 100%" max-height="450">
          <el-table-column prop="city" label="开始日期" width="120">
            <template slot-scope="scope">{{totime(scope.row.starttime)}}</template>
          </el-table-column>
          <el-table-column prop="city" label="结束日期" width="120">
            <template slot-scope="scope">{{totime(scope.row.endtime)}}</template>
          </el-table-column>
          <el-table-column prop="city" label="周期" width="120">
            <template slot-scope="scope">{{ getweak(scope.row.checkList) }}</template>
          </el-table-column>
          <el-table-column prop="schoolclasstime" label="上课时段" width="150"></el-table-column>
          <el-table-column prop="name" label="教室" width="120">
            <template
              slot-scope="scope"
            >{{getschoolclassroombyid( scope.row.schoolclassroomid).name}}</template>
          </el-table-column>
          <el-table-column prop="address" label="教师">
            <template slot-scope="scope">{{getschooluserbyid( scope.row.schooluserid).name}}</template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                @click="changeruleForm(scope.row, scope.$index)"
              >编辑</el-button>
              <el-button type="danger" size="mini" @click="tableData.splice(scope.$index, 1);">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <br />
        <br />
        <div class="text-center">
          <el-button type="primary" size="mini" @click="visibletrue">下一步</el-button>
          <el-button type="info" size="mini" @click="clear">取消</el-button>
        </div>
        <br />
        <br />
      </div>
    </div>
    <el-drawer
      :title="`课程列表   共有${myclazzschedule.length}次课`"
      :visible.sync="visible"
      placement="right"
      :size="drawersize"
    >
      <el-container style="width:1000px;">
        <el-main class="emain">
          <el-table
            :data="myclazzschedule"
            style="width: 100%"
            max-height="500"
            :row-class-name="tableRowClassName"
            class="school-table"
          >
            <el-table-column prop="city" sortable label="开始日期" width="100">
              <template slot-scope="scope">{{totime(scope.row.starttime)}}</template>
            </el-table-column>
            <el-table-column prop="city" label="星期" width="100">
              <template
                slot-scope="scope"
              >{{ ['日', '一','二', '三','四', '五','六'][(new Date(scope.row.starttime).getDay())] }}</template>
            </el-table-column>
            <el-table-column prop="schoolclasstime" label="上课时段" width="100"></el-table-column>
            <el-table-column prop="hour" label="课时" width="100"></el-table-column>
            <el-table-column prop="name" sortable label="教室" width="100">
              <template
                slot-scope="scope"
              >{{getschoolclassroombyid( scope.row.schoolclassroomid).name}}</template>
            </el-table-column>
            <el-table-column prop="address" sortable label="教师" width="100">
              <template slot-scope="scope">{{getschooluserbyid( scope.row.schooluserid).name}}</template>
            </el-table-column>
            <el-table-column prop="address" label="助教">
              <template slot-scope="scope">{{ usernameids(scope.row.schooluserids) }}</template>
            </el-table-column>
            <el-table-column prop="info" label="课程内容"></el-table-column>
            <el-table-column prop="address" sortable label="状态" width="80">
              <template slot-scope="scope">
                <div>
                  {{scope.row.ID?'已排课':"新排课"}}
                  <br />
                  {{scope.row.schoolclasshourid?'有序课程':"自由课"}}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template slot-scope="scope" v-if="!scope.row.ID">
                <el-button type="text" size="small" @click="add(scope.row)">编辑</el-button>
                <el-button type="text" size="small" @click="findindex(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
        <el-footer>
          <el-button type="primary" size="mini" @click="submit">提交</el-button>
        </el-footer>
      </el-container>
    </el-drawer>
    <el-dialog class="school-form" title="班级详情" width="510px" :visible.sync="setaddress">
      <el-form :model="rule" :rules="rules" ref="ruleForm2" label-width="100px" size="mini">
        <el-form-item label="上课日期" prop="starttime">
          <el-date-picker
            :picker-options="pickerOptions"
            v-model="rule.starttime"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="上课时段" prop="schoolclasstime">
          <el-select v-model="rule.schoolclasstime" allow-create placeholder="请选择时间段">
            <el-option
              v-for="(item, i) in returnschoolclasstime"
              :key="`12clazzschedule${i}`"
              :label="`${item.starttime}-${item.endtime}`"
              :value="`${item.starttime}-${item.endtime}`"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课时" prop="hour">
          <el-input-number v-model="rule.hour" :min="1" :max="10" label="描述文字"></el-input-number>
        </el-form-item>
        <el-form-item label="教室" prop="schoolclassroomid">
          <el-select v-model="rule.schoolclassroomid" allow-create placeholder="请选择教室">
            <el-option
              v-for="(item, i) in classroom"
              :key="`14clazzschedule${i}`"
              :label="item.name"
              :value="item.ID"
              :disabled="item.studentnum<clazz.studentnum"
            >
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">可容纳{{ item.studentnum }}人</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教师" prop="schooluserid">
          <el-select v-model="rule.schooluserid" allow-create placeholder="请选择教师">
            <el-option
              v-for="(item, i) in user"
              :key="`15clazzschedule${i}`"
              :label="item.name"
              :value="item.ID"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="助教">
          <el-select v-model="rule.schooluserids" allow-create placeholder="请选择助教">
            <el-option
              v-for="(item, i) in getschooluser.filter(v=> !v.state)"
              :key="`17clazzschedule${i}`"
              :label="item.name"
              :value="item.ID"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程内容">
          <el-input v-model="rule.info" placeholder="课程内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="sub" type="primary" plain size="mini">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import * as moment from "moment";
import {
  asynccreatschoolclazzschedule,
  asynccreateschoolclazz,
  asyncgetschoolclazzschedule,
  asynccheckconflictsschoolclazzschedule
} from "../../../../plugins/api.js";
import { sortBy, isEqual, uniq, groupBy } from "underscore";
import {
  conflictvalidator,
  totime,
  intersection,
  disabledDate
} from "../../../utils.js";
import uuid from "uuid/v4";
export default {
  name: "clazzschedule",
  data() {
    return {
      pickerOptions: {
        disabledDate
      },
      drawersize: "800",
      visible: false,
      myclass: false,
      ruleForm: {
        value1: "",
        starttime: "",
        schoolclasstime: "",
        info: "",
        schooluserids: "",
        hour: 1,
        repeat: true,
        schooluserid: "",
        schoolclassroomid: "",
        checkList: [],
        holiday: true,
        schoolclasshourid: ""
      },
      rules: {
        starttime: [{ required: true, message: "请选择时间", trigger: "blur" }],
        schoolclasstime: [
          { required: true, message: "请选择时间段", trigger: "blur" }
        ],
        schooluserid: [
          { required: true, message: "请选择教师", trigger: "blur" }
        ],
        schoolclassroomid: [
          { required: true, message: "请选择教室", trigger: "blur" }
        ],
        hour: [{ required: true, message: "添加课时", trigger: "blur" }],
        checkList: [
          { required: true, validator: this.ischeckList, trigger: "blur" }
        ]
      },
      settype: false,
      setaddress: false,
      tableData: [],
      pushdata: [],
      rule: {
        starttime: "",
        schoolclasstime: "",
        info: "",
        schooluserids: "",
        schooluserid: "",
        schoolclassroomid: "",
        index: "",
        schoolclasshourid: ""
      },
      index: undefined,
      courseindex: "", // 选择的课程
      getschoolclazzschedule: [], // 已添加课程日程
      ischeckconflicts: [], // 异常课程日程
      settableshow: true,
      freedata: []
    };
  },
  props: ["ID"],
  created() {
    this.start();
  },
  watch: {
    type() {
      this.ruleForm.starttime = "";
    },
    ID() {
      this.start();
    },
    tableData(v) {
      if (v.length === 0) {
        this.settableshow = true;
      }
    }
  },
  computed: {
    ...mapGetters([
      "getschoolclazz",
      "getschoolclassroom",
      "getschooluser",
      "getschoolclasstime",
      "getschoolholiday",
      "getschoolcourse",
      "getschoolclasshour",
      "getschoolclassroombyid",
      "getschooluserbyid"
    ]),
    type: {
      get: function() {
        return this.settype;
      },
      set: async function(v) {
        if (!v) {
          if (this.tableData.length) {
            this.$confirm("此操作将清除当前排课计划, 是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
              .then(() => {
                this.clear();
                this.settype = v;
              })
              .catch(() => {});
          } else {
            this.settype = v;
          }
        } else {
          this.settype = v;
        }
      }
    },
    clazz() {
      return this.getschoolclazz.find(v => v.ID == this.ID) || { type: 0 };
    },
    classhours() {
      if (this.clazz.schoolcourseid) {
        return this.getschoolclasshour.filter(
          v => v.schoolcourseid == this.clazz.schoolcourseid
        );
      } else {
        return this.getschoolclasshour.filter(
          v => v.schoolcourseid == this.courseindex
        );
      }
    },
    classroom() {
      let ID = this.ID;
      if (ID) {
        let { schooladdressid } = this.getschoolclazz.find(v => v.ID == ID);
        return this.getschoolclassroom.filter(
          v => v.schooladdressid == schooladdressid
        );
      }
      return [];
    },
    user() {
      let ID = this.ID;
      if (ID) {
        let { schooladdressid } = this.getschoolclazz.find(v => v.ID == ID);
        return this.getschooluser.filter(v => {
          if (v.state) return;
          if (v.isteacher == 1) {
            if (v.classscope == "*") {
              return true;
            } else {
              let x = v.classscope.split(",");
              if (x.includes(schooladdressid.toString())) {
                return true;
              }
            }
          }
        });
      }
      return [];
    },
    myclazzschedule() {
      const { pushdata, getschoolclazzschedule, classhours, freedata } = this;
      const x = [];
      x.push(...pushdata);
      x.push(...getschoolclazzschedule);

      let data = sortBy(x, v => {
        return (
          Math.round(new Date(v.starttime)) +
          Number(v.schoolclasstime.split("-")[0].split(":")[0])
        );
      });
      let index = 0;
      for (let v of data) {
        const start = Math.round(new Date(v.starttime));
        const n = Math.round(new Date()) - 24 * 3600 * 1000;
        if (start > n) {
          if (v.schoolclasshourid || !v.ID) {
            v.info = classhours[index] ? classhours[index].name : "";
            v.schoolclasshourid = classhours[index]
              ? this.classhours[index].ID
              : null;
            index++;
          }
        }
      }
      data.push(...freedata);
      data = sortBy(data, v => {
        v.schoolclazzid = this.ID;
        return (
          Math.round(new Date(v.starttime)) +
          Number(v.schoolclasstime.split("-")[0].split(":")[0])
        );
      });

      return data;
    },
    pushdatacoursenum() {
      let x = 0;
      let y = 0;
      for (let v of this.myclazzschedule) {
        if (!v.ID) {
          x += 1;
          y += v.hour;
        }
      }
      return {
        hour: y,
        length: x
      };
    },
    returnschoolclasstime() {
      const { ID, getschoolclasstime, ruleForm } = this;
      let { schooladdressid } = this.getschoolclazz.find(v => v.ID == ID);
      const n = new Date(ruleForm.starttime).getTime();
      if (n < Date.now()) {
        return getschoolclasstime.filter(v => {
          let nw = new Date().getHours() * 60 + new Date().getMinutes();
          let vw =
            Number(v.starttime.split(":")[0]) * 60 +
            Number(v.starttime.split(":")[1]);
          if (v.schooladdressid) {
            if (v.schooladdressid == schooladdressid) {
              return nw < vw;
            }
          }
          return nw < vw;
        });
      }
      return getschoolclasstime.filter(v => {
        if (v.schooladdressid) {
          return v.schooladdressid == schooladdressid;
        }
        return true;
      });
    },
    datagroup() {
      const { ischeckconflicts, pushdata, freedata } = this;
      return groupBy([...ischeckconflicts, ...pushdata, ...freedata], v =>
        new Date(v.starttime).toLocaleDateString()
      );
    }
  },
  methods: {
    async start() {
      if (this.clazz.type === "0") {
        this.$router.push({ name: "班级" });
        this.$message.error("已结课无法排课");
      }
      this.courseindex = this.clazz.schoolcourseid;
      try {
        this.getschoolclazzschedule = await asyncgetschoolclazzschedule({
          schoolclazzid: this.ID
        });
      } catch (err) {
        this.$message.error(`出错了:${err}`);
      }
    },
    clear() {
      this.tableData = [];
      this.pushdata = [];
      this.freedata = [];
      this.settableshow = true;
    },
    tableRowClassName({ row }) {
      if (row) {
        if (!row.ID) {
          const { datagroup } = this;
          const data = datagroup[new Date(row.starttime).toLocaleDateString()];
          const f = JSON.parse(JSON.stringify(data));
          if (row.index === undefined) {
            const index = f.findIndex(v => v.th === row.th);
            f.splice(index, 1);
          } else {
            const index = f.findIndex(v => v.index === row.index);
            f.splice(index, 1);
          }
          if (conflictvalidator(row, f)) {
            return "text-danger";
          }
        }
        return "";
      }
      return "";
    },
    changeruleForm(row) {
      this.settableshow = true;
      const {
        schoolclasstime,
        info,
        schoolclassroomid,
        schooluserid,
        schooluserids,
        starttime,
        value1,
        checkList,
        repeat,
        holiday,
        hour,
        schoolclasshourid,
        i
      } = JSON.parse(JSON.stringify(row));
      this.ruleForm = {
        schoolclasstime,
        info,
        schoolclassroomid,
        schooluserid,
        schooluserids,
        starttime,
        value1,
        checkList,
        repeat,
        holiday,
        hour,
        schoolclasshourid,
        i
      };
    },
    totime,
    getweak(checkList) {
      const arr = [
        { name: "一", value: 1 },
        { name: "二", value: 2 },
        { name: "三", value: 3 },
        { name: "四", value: 4 },
        { name: "五", value: 5 },
        { name: "六", value: 6 },
        { name: "日", value: 7 }
      ];
      let x = "";
      for (let v of checkList) {
        x += `周${arr[v - 1].name} `;
      }
      return x;
    },
    async submitForm() {
      const {
        schoolclasstime,
        info,
        schoolclassroomid,
        schooluserid,
        schooluserids,
        starttime,
        value1,
        checkList,
        holiday,
        repeat,
        hour,
        schoolclasshourid,
        i
      } = this.ruleForm;
      if (this.type) {
        this.ruleForm.starttime = value1[0];
      }
      this.$refs["ruleForm"].validate(async valid => {
        if (valid) {
          if (!this.type) {
            this.freedata.push({
              schoolclasstime,
              info,
              schoolclassroomid,
              schooluserid,
              schooluserids,
              starttime,
              hour,
              schoolclasshourid,
              th: uuid()
            });
          } else {
            if (i === undefined) {
              this.tableData.push({
                i: uuid(),
                schoolclasstime,
                schoolclassroomid,
                schooluserid,
                schooluserids,
                starttime: value1[0],
                endtime: value1[1],
                holiday,
                checkList,
                value1,
                hour,
                schoolclasshourid,
                repeat
              });
            } else {
              const index = this.tableData.findIndex(v => v.i === i);
              this.tableData[index] = {
                i,
                schoolclasstime,
                schoolclassroomid,
                schooluserid,
                schooluserids,
                starttime: value1[0],
                endtime: value1[1],
                holiday,
                checkList,
                value1,
                hour,
                schoolclasshourid,
                repeat
              };
            }

            this.ruleForm = {
              value1: "",
              starttime: "",
              schoolclasstime: "",
              info: "",
              schooluserids: "",
              checkList: [],
              schooluserid: "",
              schoolclassroomid: "",
              schoolclasshourid,
              hour: 1
            };
            this.settableshow = false;
            await this.list();
          }

          await this.visibletrue();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    async submit() {
      const {
        checkconflict,
        pushdata,
        freedata,
        getschoolclazzschedule
      } = this;
      const data = [...pushdata, ...freedata];
      if (data.length) {
        await checkconflict();

        for (let v of data) {
          const d = this.tableRowClassName({ row: v });
          if (d) {
            this.$message.error("请将修改冲突的课程,或者删除");
            return;
          }
        }
      } else {
        this.visible = false;
        return;
      }
      this.visible = false;
      this.$notify({
        title: "排课状态",
        message: "排课中"
      });
      if (this.$store.state.state) return;
      this.$store.commit("setstate", true);

      if (this.myclazzschedule.length > 200) {
        this.$message.error("排课将超过最多添加课次,请删除多出课程");
        return false;
      }

      try {
        for (let v of this.myclazzschedule) {
          const {
            ID,
            hour,
            info,
            name,
            schoolclasshourid,
            schoolclassroomid,
            schoolclasstime,
            schooluserid,
            schooluserids,
            starttime
          } = v;
          const fromdata = {
            ID,
            hour,
            info,
            name,
            schoolclasshourid,
            schoolclassroomid,
            schoolclasstime,
            schooluserid,
            schooluserids,
            starttime
          };
          const d = getschoolclazzschedule.find(vo => {
            const {
              ID,
              hour,
              info,
              name,
              schoolclasshourid,
              schoolclassroomid,
              schoolclasstime,
              schooluserid,
              schooluserids,
              starttime
            } = vo;
            const indexdata = {
              ID,
              hour,
              info,
              name,
              schoolclasshourid,
              schoolclassroomid,
              schoolclasstime,
              schooluserid,
              schooluserids,
              starttime
            };
            return isEqual(fromdata, indexdata);
          });

          if (!d) {
            const start = Math.round(new Date(v.starttime));
            const n = Math.round(new Date()) - 1000 * 3600 * 24;
            if (start > n) {
              v.schoolclazzid = this.ID;
              await asynccreatschoolclazzschedule(v);
            }
          }
        }
      } catch (err) {
        console.log(err);
      }
      this.clear();

      this.$notify({
        type: "success",
        title: "排课状态",
        message: "排课成功"
      });
      await this.start();
      this.$store.commit("setstate", false);
    },
    add(v) {
      this.setaddress = true;
      this.title = "修改";
      this.rule = JSON.parse(JSON.stringify(v));
    },
    async visibletrue() {
      await this.list();
      if (!this.clazz.schoolcourseid && this.courseindex) {
        await asynccreateschoolclazz({
          ID: this.clazz.ID,
          schoolcourseid: this.courseindex
        });
        await this.$store.dispatch("actionschoolclazz");
      }
      await this.checkconflict();
      this.visible = true;
    },
    async checkconflict() {
      const { freedata, pushdata } = this;
      const v = [...freedata, ...pushdata];
      if (v.length) {
        if (this.myclazzschedule.length > 200) {
          this.$message.error(
            "每个班级最多可以添加200次课程，此次排课将超过会无法提交"
          );
          return;
        }
        const data = sortBy(v, x => Math.round(new Date(x.starttime)));
        const starttime = data[0].starttime;
        const endtime = data[data.length - 1].starttime;
        this.ischeckconflicts = await asynccheckconflictsschoolclazzschedule({
          starttime,
          endtime
        });
      }
    },
    sub() {
      this.$refs["ruleForm2"].validate(async valid => {
        if (valid) {
          // 获取修改结果
          const y = JSON.parse(JSON.stringify(this.rule));
          // 判断是否是freedata
          const { freedata, pushdata } = this;
          if (y.index === undefined) {
            const index = freedata.findIndex(v => v.th === y.th);
            freedata.splice(index, 1, y);
          } else {
            const index = pushdata.findIndex(v => v.index === y.index);
            // 判断是否修改info
            if (y.info !== pushdata[index].info) {
              // 删除index 、关联
              delete y.index;
              delete y.schoolclasshourid;
              y.th = uuid();
              freedata.push(y);
              // 重新修改pushdata
              pushdata.splice(index, 1);
            } else {
              pushdata.splice(index, 1, y);
            }
          }
          this.setaddress = false;
        }
      });
    },
    async list() {
      this.pushdata = [];
      const pushdata = [];
      for (let v of this.tableData) {
        const {
          value1,
          holiday,
          repeat,
          schoolclasstime,
          schooluserids,
          schooluserid,
          schoolclassroomid,
          schoolclazzid,
          checkList,
          hour
        } = v;
        let day = 7;
        if (!repeat) {
          day = 14;
        }
        const s =
          Math.round(new Date(value1[1])) - Math.round(new Date(value1[0]));
        // 获取时间差中有几周
        const asWeeks = moment.duration(s).asWeeks();
        for (let v = 0; v < asWeeks; v++) {
          for (let i of checkList) {
            const starttime =
              moment(value1[0])
                .day(day * v + i)
                .unix() * 1000;
            let x =
              starttime >= Math.round(new Date(value1[0])) &&
              starttime <= Math.round(new Date(value1[1]));
            let y = false;
            if (!holiday) {
              y = this.getschoolholiday.find(v => {
                return intersection(
                  { s: starttime, e: starttime },
                  {
                    s: Math.round(new Date(v.starttime)),
                    e: Math.round(new Date(v.endtime))
                  }
                );
              });
            }
            if (x && !y) {
              // if (!y) {
              pushdata.push(
                JSON.stringify({
                  starttime: new Date(starttime),
                  schoolclasstime,
                  schooluserids,
                  schooluserid,
                  schoolclassroomid,
                  schoolclazzid,
                  hour
                })
              );
            }
          }
        }
      }

      const arr = uniq(pushdata);
      this.pushdata = arr.map(v => {
        const d = JSON.parse(v);
        return {
          index: uuid(),
          ...d
        };
      });
    },

    ischeckList(_rule, _value, callback) {
      if (this.type) {
        if (this.ruleForm.checkList.length == 0) {
          callback(new Error("最少选择一天"));
          return;
        }
        callback();
      }
      callback();
    },
    usernameids(id) {
      if (id) {
        const data = this.getschooluser.find(v => v.ID == id);
        return data ? data.name : "";
      }
      return "";
    },
    findindex(row) {
      const { pushdata, freedata } = this;
      if (row.index === undefined) {
        freedata.splice(freedata.findIndex(v => v.th == row.th), 1);
      } else {
        pushdata.splice(pushdata.findIndex(v => v.index == row.index), 1);
      }
    }
  },
  beforeDestroy() {
    this.$store.dispatch("actionschoolclazz");
  }
};
</script>

<style lang="scss" scoped>
.index-model {
  margin-top: 13px;
}
.emain {
  overflow-y: auto;
}
</style>